<?php
/**
 * Date: 2024.8
 * Author: kahn
 * 路由验证插件, 执行:
 * 1. 路由检查
 * 2. 参数校验
 * 3. 签名验证
 * 4. 将传入参数填充进GCommon全局实例
 */
use config\Route;
use plugins\Plugin;
use service\uc\JwtService;
use config\Response;

class RoutePlugin extends Yaf_Plugin_Abstract {

    use Plugin;

    public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {

        $route = $this->getRoute();
        $method = $this->getMethod();

        $this->routed($method, $route);

        $this->validate($method, $route);

        $this->sign($method, $route);

        $realUri = Route::ROUTE[$method][$route]['real'];

        $this->setRoue($request, $realUri);
    }

    private function setRoue(Yaf_Request_Abstract $request, $route)
    {   $request->setRequestUri($route);

    }

    private function routed($method, $route): void
    {
        if(!isset(Route::ROUTE[$method][$route])){
            header('HTTP/1.1 404 Not Found');
            die('404 Not Found');
        }
    }

    private function validate($method, $route): void
    {
        $validate = new Validator($method, $route);
        $validate->rule(Route::getRule($method, $route));

        if(Route::needCommon($method, $route)){
            $validate->rule(GCommon->getRule());
        }

        $body = file_get_contents("php://input");
        if($body){
            $data = json_decode(file_get_contents("php://input"), true);
            if($data){
                if(!$validate->check($data)){
                    response(Response::PARAMS_ERROR, ['tip'=>$validate->getError()]);
                }
                GCommon->setData($data);
            }
        }
    }

    private function sign($method, $route){
        $sign = Yaf_Registry::get('config')->sign;
        if($sign->on == 1 && Route::needSign($method, $route)){

            if (!isset($_SERVER['HTTP_CCSS'])) {
                response(Response::SIGN_ERROR);
            }
            $body = GCommon->getData();
            ksortRecursive($body);
            $str = arrayToString($body, $sign->key);
            if (md5($str) != $_SERVER['HTTP_CCSS']) {
                response(Response::SIGN_ERROR);
            }
        }
    }
}
